//require CN1MP3Encoder
package com.codename1.samples;


import com.codename1.io.File;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.io.NetworkEvent;
import com.codename1.media.Media;
import com.codename1.media.MediaManager;
import com.codename1.ui.Button;
import com.codename1.ui.Slider;
import com.codename1.ui.util.UITimer;

/**
 * This file was generated by <a href="https://www.codenameone.com/">Codename One</a> for the purpose 
 * of building native mobile applications using Java.
 */
public class CreateMediaRecorderSample {

    private Form current;
    private Resources theme;
    
    
            

    public void init(Object context) {
        // use two network threads instead of one
        updateNetworkThreadCount(2);

        theme = UIManager.initFirstTheme("/theme");

        // Enable Toolbar on all Forms by default
        Toolbar.setGlobalToolbar(true);

        // Pro only feature
        Log.bindCrashProtection(true);

        addNetworkErrorListener(err -> {
            // prevent the event from propagating
            err.consume();
            if(err.getError() != null) {
                Log.e(err.getError());
            }
            Log.sendLogAsync();
            Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
        });        
    }
    
    Button play;
    Button record;
    Button pause;
    Button reset;
    Slider slider;
    Media playMedia, recordMedia;
    private boolean recording, playing;
    com.codename1.io.File mediaFile;
    String mimetype;
    UITimer sliderUpdater;
    
    private void update() {
        if (recording) {
            play.setEnabled(false);
            record.setEnabled(false);
            pause.setEnabled(true);
            reset.setEnabled(false);
            slider.setEnabled(false);
            
        } else if (playing) {
            play.setEnabled(false);
            record.setEnabled(false);
            pause.setEnabled(true);
            reset.setEnabled(false);
            slider.setEnabled(true);
        } else if (playMedia != null) {
            play.setEnabled(true);
            record.setEnabled(false);
            pause.setEnabled(false);
            reset.setEnabled(true);
            slider.setEnabled(true);
        } else {
            record.setEnabled(true);
            play.setEnabled(false);
            pause.setEnabled(false);
            reset.setEnabled(false);
            slider.setEnabled(false);
        }
        play.getComponentForm().repaint();
    }
    
    public void start() {
        if(current != null){
            current.show();
            return;
        }
        mediaFile = new File("myrecording");
        play = new Button("Play");
        record = new Button("Record");
        pause = new Button("Pause");
        reset = new Button("Reset");
        slider = new Slider();
        
        Form hi = new Form("Hi World", BoxLayout.y());
        hi.addAll(record, play, pause, reset, slider);
        
        record.addActionListener(e->{
            if (recordMedia != null || playing || playMedia != null) {
                return;
            }
            
            recordMedia = null;
            try {
                mimetype = MediaManager.getAvailableRecordingMimeTypes()[0];
                recordMedia = MediaManager.createMediaRecorder(mediaFile.getAbsolutePath(), mimetype);
                recordMedia.play();
                recording = true;
                update();
            } catch (IOException ex) {
                Log.e(ex);
            }
        });
        
        pause.addActionListener(e->{
            if (sliderUpdater != null) {
                sliderUpdater.cancel();
                sliderUpdater = null;
            }
            if (recording) {
                recordMedia.pause();
                recording = false;
                com.codename1.io.FileSystemStorage fs = com.codename1.io.FileSystemStorage.getInstance();
                try {
                    playMedia = MediaManager.createMedia(fs.openInputStream(mediaFile.getAbsolutePath()), mimetype, ()->{
                        playing = false;
                        if (sliderUpdater != null) {
                            sliderUpdater.cancel();
                            sliderUpdater = null;
                        }
                        update();
                    });
                    slider.setMinValue(0);
                    slider.setMaxValue(playMedia.getDuration());
                    update();
                    
                } catch (IOException ioe) {
                    Log.e(ioe);
                }
            } else if (playing) {
                playMedia.pause();
                playing = false;
                update();
            } 
        });
        
        play.addActionListener(e->{
            if (recording || playing) {
                return;
            }
            if (playMedia != null) {
                playMedia.setTime(0);
                playMedia.play();
                playing = true;
                sliderUpdater = UITimer.timer(500, true, ()->{
                    if (playMedia != null) {
                        slider.setProgress(playMedia.getTime());
                        slider.repaint();
                    }
                });
                update();
            }
        });
        
        reset.addActionListener(e->{
            if (sliderUpdater != null) {
                sliderUpdater.cancel();
                sliderUpdater = null;
            }
            if (playMedia != null) {
                playMedia.pause();
                playMedia.cleanup();
                playMedia = null;
            }
            if (recordMedia != null) {
                recordMedia.pause();
                recordMedia.cleanup();
                recordMedia = null;
            }
            
            
            mediaFile.delete();
            update();
            
        });
        
        slider.addActionListener(e->{
            if (playMedia != null) {
                playMedia.setTime(slider.getProgress());
            }
        });
        hi.show();
    }

    public void stop() {
        current = getCurrentForm();
        if(current instanceof Dialog) {
            ((Dialog)current).dispose();
            current = getCurrentForm();
        }
    }
    
    public void destroy() {
    }

}
